<template>
  <a-modal :title="form.apiId ? '编辑' : '添加'" width="600px" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }">
      <a-row>
        <a-col :span="24">
          <a-form-item label="API接口名称" name="apiName">
            <a-input style="width: 100%" v-model:value="form.apiName" placeholder="请输入API接口名称" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="开放主题" name="apiTopic">
            <a-input style="width: 100%" v-model:value="form.apiTopic" placeholder="请输入MQTT主题" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="关联数据模型" name="modelId">
            <a-select ref="select" v-model:value="form.modelId" placeholder="请选择关联数据模型">
              <a-select-option v-for="item in modelList" :key="item.modelId" :value="item.modelId">
                {{ item.modelName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="输出协议" name="protocol">
            <a-select ref="select" v-model:value="form.protocol" placeholder="请选择输出协议" @change="protocolChange">
              <a-select-option v-for="item in outputDataTypeDict" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="接口描述" name="description">
            <a-textarea :rows="4" style="width: 100%" v-model:value="form.description" placeholder="请输入接口描述" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <FormComponents ref="FormComponentsRef" :form="form" />

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { reactive, ref, nextTick, onMounted } from 'vue';
  import { defineProps } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { iotApi } from '/@/api/plat/dataApi';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { PageMixin } from '/@/utils/mixin';
  const { resetForm } = PageMixin();
  import { outputDataTypeDict } from '/@/assets/js/dict';

  import FormComponents from '/@/components/formComponents/index.vue';

  // ------------------------ 事件 ------------------------
  const emits = defineEmits(['reloadList']);
  defineProps({
    modelList: {
      type: Array,
      required: true,
    },
  });
  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  const FormComponentsRef = ref();
  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    resetForm(form, formDefault);
    visibleFlag.value = false;
  }

  // 组件ref
  const formRef = ref();

  const formDefault = {
    ruleName: undefined,
    modelId: undefined,
    description: undefined,
  };

  let form = reactive({ ...formDefault });

  const rules = {
    apiName: [{ required: true, message: '请填写API接口名称' }],
    apiTopic: [{ required: true, message: '请填写MQTT主题' }],
    modelId: [{ required: true, message: '请选择关联数据模型' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save(form);
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save(formData) {
    SmartLoading.show();
    try {
      if (formData.apiId) {
        await iotApi.update(formData);
      } else {
        formData.ts = +new Date();
        await iotApi.add(formData);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  function protocolChange(val) {
    const row = outputDataTypeDict.find((m) => m.id === val);
    const content = JSON.parse(row.content);
    let list = [];
    for (let key in content) {
      list.push(Object.assign({}, { key }, content[key]));
    }
    FormComponentsRef.value.setOptions(list);
  }

  defineExpose({
    show,
  });
</script>

<style scoped>
  .ant-select {
    width: 100% !important;
  }
</style>
